#!/bin/bash

# Gemini CLI - 一键安装脚本
# 自动构建并安装到本地

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

print_banner() {
    echo -e "${CYAN}"
    cat << "EOF"
╔═══════════════════════════════════════════════╗
║     Gemini CLI - 国内大模型版               ║
║     快速安装脚本                            ║
╚═══════════════════════════════════════════════╝
EOF
    echo -e "${NC}"
}

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}$1${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
}

check_requirements() {
    print_step "检查系统要求"
    
    # 检查 Node.js
    if ! command -v node &> /dev/null; then
        print_error "未找到 Node.js"
        print_info "请安装 Node.js >= 20.0.0"
        print_info "下载地址: https://nodejs.org/"
        exit 1
    fi
    
    NODE_VERSION=$(node --version | cut -d 'v' -f 2)
    print_success "Node.js 版本: $NODE_VERSION"
    
    # 检查 npm
    if ! command -v npm &> /dev/null; then
        print_error "未找到 npm"
        exit 1
    fi
    
    NPM_VERSION=$(npm --version)
    print_success "npm 版本: $NPM_VERSION"
}

install_dependencies() {
    print_step "安装项目依赖"
    
    print_info "执行 npm install..."
    if npm install; then
        print_success "依赖安装完成"
    else
        print_error "依赖安装失败"
        exit 1
    fi
}

build_project() {
    print_step "构建项目"
    
    # 清理旧的构建
    print_info "清理旧的构建文件..."
    if npm run clean 2>/dev/null; then
        print_success "清理完成"
    else
        print_warning "清理失败，继续构建..."
    fi
    
    # 构建项目
    print_info "构建项目..."
    if npm run build; then
        print_success "项目构建完成"
    else
        print_error "项目构建失败"
        print_info "请查看上面的错误信息"
        exit 1
    fi
}

install_global() {
    print_step "安装到全局"
    
    # 询问安装方式
    echo ""
    echo "请选择安装方式:"
    echo "  1) npm link (推荐开发使用，便于更新)"
    echo "  2) npm install -g (全局安装)"
    echo ""
    read -p "请输入选择 [1-2] (默认: 1): " choice
    choice=${choice:-1}
    
    case $choice in
        1)
            print_info "使用 npm link 安装..."
            if npm link; then
                print_success "npm link 完成"
            else
                print_warning "npm link 失败，尝试使用 sudo"
                if sudo npm link; then
                    print_success "npm link 完成 (使用 sudo)"
                else
                    print_error "安装失败"
                    exit 1
                fi
            fi
            ;;
        2)
            print_info "使用 npm install -g 安装..."
            if npm install -g .; then
                print_success "全局安装完成"
            else
                print_warning "安装失败，尝试使用 sudo"
                if sudo npm install -g .; then
                    print_success "全局安装完成 (使用 sudo)"
                else
                    print_error "安装失败"
                    exit 1
                fi
            fi
            ;;
        *)
            print_error "无效的选择"
            exit 1
            ;;
    esac
}

setup_config() {
    print_step "配置环境"
    
    CONFIG_DIR="$HOME/.gemini"
    CONFIG_FILE="$CONFIG_DIR/.env"
    
    if [ ! -f "$CONFIG_FILE" ]; then
        print_info "创建配置目录: $CONFIG_DIR"
        mkdir -p "$CONFIG_DIR"
        
        print_info "创建配置文件: $CONFIG_FILE"
        cp env.example "$CONFIG_FILE"
        
        print_success "配置文件已创建"
        print_warning "请编辑配置文件并填入你的 API Key:"
        echo ""
        echo "  配置文件位置: $CONFIG_FILE"
        echo ""
        echo "  编辑命令:"
        echo "    nano $CONFIG_FILE"
        echo "    或"
        echo "    vim $CONFIG_FILE"
        echo ""
        
        read -p "是否现在编辑配置文件? [y/N]: " edit_now
        if [[ $edit_now =~ ^[Yy]$ ]]; then
            if command -v nano &> /dev/null; then
                nano "$CONFIG_FILE"
            elif command -v vim &> /dev/null; then
                vim "$CONFIG_FILE"
            else
                print_warning "未找到文本编辑器，请手动编辑配置文件"
            fi
        fi
    else
        print_info "配置文件已存在: $CONFIG_FILE"
    fi
}

verify_installation() {
    print_step "验证安装"
    
    if command -v gemini &> /dev/null; then
        print_success "gemini 命令已可用"
        
        # 显示版本
        print_info "版本信息:"
        gemini --version
        
        # 显示安装位置
        print_info "安装位置: $(which gemini)"
    else
        print_error "gemini 命令不可用"
        print_info "请检查 PATH 环境变量"
        print_info "npm 全局 bin 目录: $(npm bin -g)"
        exit 1
    fi
}

show_next_steps() {
    print_step "安装完成！"
    
    echo ""
    echo -e "${GREEN}✓ Gemini CLI 已成功安装到本地${NC}"
    echo ""
    echo "接下来的步骤:"
    echo ""
    echo "1️⃣  配置 API Key (如果还没配置)"
    echo "   编辑: ~/.gemini/.env"
    echo ""
    echo "2️⃣  测试配置"
    echo "   运行: ./test-chinese-llm.sh"
    echo ""
    echo "3️⃣  启动 Gemini CLI"
    echo "   运行: gemini"
    echo "   或: ./start-chinese-llm.sh"
    echo ""
    echo "📚 查看文档:"
    echo "   - 配置指南: ./CHINESE_LLM_SETUP.md"
    echo "   - 使用说明: ./README_CN.md"
    echo "   - 构建文档: ./BUILD_AND_INSTALL.md"
    echo ""
    echo "🔧 常用命令:"
    echo "   gemini              # 启动 CLI"
    echo "   gemini --help       # 查看帮助"
    echo "   gemini --version    # 查看版本"
    echo ""
    
    # 如果配置文件为空或未配置
    if [ -f "$HOME/.gemini/.env" ]; then
        if ! grep -q "API_KEY=" "$HOME/.gemini/.env" | grep -v "^#" | grep -v "xxx"; then
            print_warning "提醒: 请配置 API Key 后再使用"
        fi
    fi
}

main() {
    print_banner
    
    # 检查是否在项目根目录
    if [ ! -f "package.json" ]; then
        print_error "请在项目根目录下运行此脚本"
        exit 1
    fi
    
    print_info "开始安装 Gemini CLI..."
    echo ""
    
    # 执行安装步骤
    check_requirements
    install_dependencies
    build_project
    install_global
    setup_config
    verify_installation
    show_next_steps
    
    print_success "安装流程完成！🎉"
}

# 运行主函数
main "$@"

